package com.ruoyi.edit.service.impl;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.edit.domain.*;
import com.ruoyi.edit.mapper.*;
import com.ruoyi.edit.service.ITcVendorCourseUserRecordService;
import com.ruoyi.edit.utils.CopyUtils;
import com.ruoyi.edit.utils.ExcelOperateUtil;
import com.ruoyi.edit.utils.UuidUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.edit.service.IVendorCourseService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 课程Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-03-07
 */
@Service
public class VendorCourseServiceImpl implements IVendorCourseService 
{
    @Autowired
    private VendorCourseMapper vendorCourseMapper;

    @Autowired
    private AbilityMapper abilityMapper;

    @Autowired
    private CoursePackageMapper coursePackageMapper;

    @Autowired
    private  CourseToolMapper courseToolMapper;

    @Autowired
    private VendorCourseRelMapper vendorCourseRelMapper;

    @Autowired
    private ITcVendorCourseUserRecordService tcVendorCourseUserRecordService;
    /**
     * 查询课程
     * 
     * @param id 课程主键
     * @return 课程
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public VendorCourse selectVendorCourseById(String id)
    {
        return vendorCourseMapper.selectVendorCourseById(id);
    }

    /**
     * 查询课程列表
     * 
     * @param vendorCourse 课程
     * @return 课程
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public List<VendorCourse> selectVendorCourseList(VendorCourse vendorCourse)
    {
        if (Objects.nonNull(vendorCourse.getAge()) && !StringUtils.equals("",vendorCourse.getAge())) {
            String[] ages = vendorCourse.getAge().split("-");
            if (ages.length>1){
                Integer ageLow = Integer.valueOf(ages[0]);
                Integer ageHigh = Integer.valueOf(ages[1]);
                vendorCourse.setAgeLow(ageLow);
                vendorCourse.setAgeHigh(ageHigh);
            }else {
                vendorCourse.setAgeLow(Integer.valueOf(vendorCourse.getAge()));
                vendorCourse.setAgeHigh(Integer.valueOf(vendorCourse.getAge()));
                vendorCourse.setAge(null);
            }
        }
        return vendorCourseMapper.selectVendorCourseList(vendorCourse);
    }

    /**
     * 新增课程
     * 
     * @param vendorCourse 课程
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public VendorCourse insertVendorCourse(VendorCourse vendorCourse)
    {
        vendorCourse.setId(UuidUtil.getUuid());
        vendorCourse.setDeleted(0);
        vendorCourse.setCreated(new Date());
        vendorCourse.setCreatedBy(ShiroUtils.getLoginName());
        vendorCourse.setCreatedName(ShiroUtils.getName());
        vendorCourseMapper.insertVendorCourse(vendorCourse);
        return vendorCourse;
    }

    /**
     * 修改课程
     * 
     * @param vendorCourse 课程
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int updateVendorCourse(VendorCourse vendorCourse)
    {
        TcVendorCourseUserRecord tcVendorCourseUserRecord = new TcVendorCourseUserRecord();
        tcVendorCourseUserRecord.setVendorCourseId(vendorCourse.getId());
        tcVendorCourseUserRecordService.insertTcVendorCourseUserRecord(tcVendorCourseUserRecord);
        return vendorCourseMapper.updateVendorCourse(vendorCourse);
    }

    /**
     * 批量删除课程
     * 
     * @param ids 需要删除的课程主键
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int deleteVendorCourseByIds(String ids)
    {
        return vendorCourseMapper.deleteVendorCourseByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除课程信息
     * 
     * @param id 课程主键
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int deleteVendorCourseById(String id)
    {
        return vendorCourseMapper.deleteVendorCourseById(id);
    }


    @Override
    @Transactional
    @DataSource(value = DataSourceType.SLAVE)
    public void importTemplate(MultipartFile file) throws Exception{
        InputStream input = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook book = ExcelOperateUtil.getWorkbook(input,fileName);
        Sheet sheet = book.getSheetAt(0);
        List<CoursePackage> vendorCoursePackageList = new ArrayList<>();
        List<VendorCourseRel> vendorCourseRelList  = new ArrayList<>();
        String label = "";
        String coursePackageId = "";
        for (int i = 0 ; i < sheet.getLastRowNum(); i++) {
            Row row1 = sheet.getRow(i+1);

            List<Map> mapList = new ArrayList<>();
            //类型
            Cell cell1 = row1.getCell(0);
            String cellValue1 = "";
            if (Objects.nonNull(cell1)){
                cell1.setCellType(CellType.STRING);
                cellValue1 = cell1.getStringCellValue();
                if (! StringUtils.equals("",cellValue1)){
                    label =  cellValue1;
                }
            }
            //月龄
            Cell cell2 = row1.getCell(1);
            String cellValue2 = "";
            if (Objects.nonNull(cell2)){
                cell2.setCellType(CellType.STRING);
                cellValue2 = cell2.getStringCellValue();

            }
            //周
            Cell cell3 = row1.getCell(2);
            String cellValue3 = "";
            if (Objects.nonNull(cell3)){
                cell3.setCellType(CellType.STRING);
                cellValue3 = cell3.getStringCellValue();
                Map map = new HashMap();
                map.put("title","周");
                map.put("content",cellValue3);
                map.put("type","richtext");
                mapList.add(map);
            }
            //预计时间
            Cell cell4 = row1.getCell(3);
            String cellValue4 = "";
            if (Objects.nonNull(cell4)){
                cell4.setCellType(CellType.STRING);
                cellValue4 = cell4.getStringCellValue();
                Map map = new HashMap();
                map.put("title","预计时间");
                map.put("content",cellValue4);
                map.put("type","richtext");
                mapList.add(map);
            }
            //标题/活动名
            Cell cell5 = row1.getCell(4);
            String cellValue5 = "未定义";
            if (Objects.nonNull(cell5)){
                cell5.setCellType(CellType.STRING);
                cellValue5 = cell5.getStringCellValue();
            }
            //课程能力指标
            Cell cell6 = row1.getCell(5);
            String cellValue6 = "";
            String abilityIds = "";
            if (Objects.nonNull(cell6)){
                cell6.setCellType(CellType.STRING);
                cellValue6 = cell6.getStringCellValue();
                cellValue6 = cellValue6.replace("\uF06C","");
                Map map = new HashMap();
                map.put("title","课程能力指标");
                map.put("content",cellValue6);
                map.put("type","richtext");
                mapList.add(map);
                //能力指标集合
                List<Ability> abilityList = new ArrayList<>();
                String[] cellValue_6 = cellValue6.split("\n");
                for (int j = 0; j < cellValue_6.length; j++) {
                    //能力指标
                    Ability ability = new Ability();
                    ability.setId(UuidUtil.getUuid());
                    ability.setDeleted(0);
                    ability.setCreated(new Date());
                    ability.setStartTime(Long.parseLong(cellValue2) * 30  -30 );
                    ability.setEndTime(Long.parseLong(cellValue2) * 30);
                    ability.setItem("0");
                    ability.setLabel(label);
                    ability.setName(cellValue_6[j]);
                    abilityMapper.insertAbility(ability);
                    //添加能力指标
                    abilityList.add(ability);
                }
                List<String> ids = abilityList.stream().map(k->k.getId()).collect(Collectors.toList());
                abilityIds = String.join(",", ids );
            }
            //内容
            Cell cell7 = row1.getCell(6);
            String cellValue7 = "";
            if (Objects.nonNull(cell7)){
                cell7.setCellType(CellType.STRING);
                cellValue7 = cell7.getStringCellValue();
                Map map = new HashMap();
                map.put("title","课程内容");
                map.put("content",cellValue7);
                map.put("type","richtext");
                mapList.add(map);
            }
            //※注意事项
            Cell cell8 = row1.getCell(7);
            String cellValue8 = "";
            if (Objects.nonNull(cell8)){
                cell8.setCellType(CellType.STRING);
                cellValue8 = cell8.getStringCellValue();
                Map map = new HashMap();
                map.put("title","注意事项");
                map.put("content",cellValue8);
                map.put("type","richtext");
                mapList.add(map);
            }

            List<Map> mapList1 = new ArrayList<>();
            //教具
            Cell cell9 = row1.getCell(8);
            String cellValue9 = "";
            String[] cellValue_9  = new String[0];
            if (Objects.nonNull(cell9)){
                cell9.setCellType(CellType.STRING);
                cellValue9 = cell9.getStringCellValue();
                cellValue_9 = cellValue9.split("\n");
            }
            //教具 - 媒体/附件
            Cell cell10 = row1.getCell(9);
            String cellValue10 = "";
            String[] cellValue_10  = new String[0];
            if (Objects.nonNull(cell10)){
                cell10.setCellType(CellType.STRING);
                cellValue10 = cell10.getStringCellValue();
                cellValue_10 = cellValue10.split("\n");
            }

            for (int j = 0; j < cellValue_9.length; j++) {
                Map map = new HashMap();
                map.put("name",cellValue_9[j]);
                map.put("number",1);
                if (j < cellValue_10.length){
                    map.put("imgUrl",cellValue_10[j]);
                }
                map.put("unit","件");
                map.put("userName","所有");
                mapList1.add(map);
            }

            //课程包
            CoursePackage vendorCoursePackage = new CoursePackage();
            if (!StringUtils.equals(cellValue1,"")){
                vendorCoursePackage.setPrice(Long.valueOf(0));
                vendorCoursePackage.setName(cellValue1);
                vendorCoursePackage.setDimensions(cellValue2);
                vendorCoursePackage.setId(UuidUtil.getUuid());
                vendorCoursePackage.setDeleted(0);
                vendorCoursePackage.setCreated(new Date());
                CoursePackage vendorCoursePackage2 =  coursePackageMapper.findByNameAndDimensionsAndPrice(cellValue1,cellValue2, Long.valueOf(0));
                if (Objects.isNull(vendorCoursePackage2)){
                    //添加课程包
                    coursePackageMapper.insertCoursePackage(vendorCoursePackage);
                }else {
                    vendorCoursePackage.setId(vendorCoursePackage2.getId());
                }
                //课程包id
                coursePackageId = vendorCoursePackage.getId();
                vendorCoursePackageList.add(vendorCoursePackage);
            }


            //课程
            VendorCourse vendorCourse = new VendorCourse();
            vendorCourse.setId(UuidUtil.getUuid());
            vendorCourse.setDeleted(0);
            vendorCourse.setCreated(new Date());
            vendorCourse.setCoursePackageId(coursePackageId);
            vendorCourse.setCover("");
            vendorCourse.setTags("");
            vendorCourse.setTitle(cellValue5);
            String str = JSON.toJSONString(mapList);
            vendorCourse.setContentTemplate(str);
            String str1 = JSON.toJSONString(mapList1);
            vendorCourse.setTools(str1);
            //添加课程,
            vendorCourseMapper.insertVendorCourse(vendorCourse);

            //课程关联
            VendorCourseRel vendorCourseRel = new VendorCourseRel();
            if (!StringUtils.equals(abilityIds,"")){
                vendorCourseRel.setId(UuidUtil.getUuid());
                vendorCourseRel.setDeleted(0);
                vendorCourseRel.setCreated(new Date());
                vendorCourseRel.setAbilityIds(abilityIds);
                vendorCourseRel.setVendorCourseId(vendorCourse.getId());
                vendorCourseRelList.add(vendorCourseRel);
            }

            for (int j = 0; j < cellValue_9.length; j++) {
                CourseTool courseTool = new CourseTool();
                courseTool.setId(UuidUtil.getUuid());
                courseTool.setDeleted(0);
                courseTool.setCreated(new Date());
                if (j < cellValue_10.length){
                    courseTool.setImgUrl(cellValue_10[j]);
                }

                courseTool.setTitle(cellValue_9[j]);
                courseTool.setUnit("件");
                courseToolMapper.insertCourseTool(courseTool);
            }

        }
        //批量保存信息
        vendorCourseRelMapper.batchVendorCourseRel(vendorCourseRelList);
    }
}
